from flask import Blueprint, render_template, request, url_for, session
from flask_login import login_required, login_user, logout_user
from flask_restful import reqparse, abort, Api, Resource
from functools import wraps

from myflaskapp.user.models import User,Role
from myflaskapp.extensions import auth,login_manager

blueprint = Blueprint('api', __name__, static_folder='../static',static_url_path='')

api = Api(blueprint)

def check_role(rolename):
    def decrator(func):
        @wraps(func)
        def wrapper(*args,**kwargs):
            if g.current_user.role.name == rolename:
                return func(*args,**kwargs)
            else:
                return {'code': 1, 'message': "无此权限！"}
        return wrapper
    return decrator

@auth.verify_password
def verify_password(account, password):
    if account and password:
        user = User.query.filter_by(username=account).first()
        if user is not None and user.verify_password(password):
            g.current_user = user
            return True
        else:
            return False
    else:
        token = request.headers.get('X-Token')
        if token == '':
            return False
        else:
            user = User.verify_auth_token(token)
            g.current_user = user
            if 'username' in session and session['username'] is not None:
                return session['username'] == user.id
            else:
                return False
	
parser = reqparse.RequestParser()
parser.add_argument('username')
parser.add_argument('password')


class Login(Resource):

    def get(self):
        return {'success': 0}

    def post(self):
        args = parser.parse_args()
        user = User.query.filter_by(username=args['username']).first()
        if user is not None and user.verify_password(args['password']):
            login_user(user)
            session['username'] = user.id
            return {'success': 1}
        else:
            return {'success': 0}


class Logout(Resource):
    @auth.login_required
    def post(self):
        logout_user()
        return {'code': 20000, 'data': 'success'}


class Token(Resource):
    @login_required
    def get(self):
        token = User.query.filter_by(id=session['username']).first(
        ).generate_auth_token(expiration=5400)
        return {'code': 20000, 'data': {'token': token}}


class Roleget(Resource):
    @auth.login_required
    def get(self):
        role = User.query.filter_by(id=session['username']).first().role
        if not role:
            return {'code': 60204, 'message': '非法用户，无法获取角色'}
        else:
            data = {}
            data['roles'] = [role.name]
            data['introduction'] = role.introduction
            data['avatar'] = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
            data['name'] = [role.name]
            return {'code': 20000, 'data': data}

class Test(Resource):
    def get(self):
        return {'data':'success'}

api.add_resource(Test,'/test',endpoint='testapi')
api.add_resource(Login, '/login', endpoint='loginapi')
api.add_resource(Logout, '/prod-api/user/logout', endpoint='logoutapi')
api.add_resource(Token, '/prod-api/user/get_token', endpoint='tokenapi')
api.add_resource(Roleget, '/prod-api/user/info', endpoint='rolegetapi')